<template>
  <div>
    <el-divider></el-divider>
    <el-switch
      style="left: 100px; "
      v-model="draggable"
      active-text="开启拖拽"
      inactive-text="关闭拖拽">
    </el-switch>
    <el-button @click="batchSave" v-if="draggable"  style="margin-left: 100px; ">批量保存</el-button>
    <el-button type="danger" @click="batchDelete" v-if="draggable"  style="margin-left: 100px; ">批量删除</el-button>
    <el-divider></el-divider>
    <el-tree :data="categoryTree" :props="defaultProps"
             :expand-on-click-node="false"
             show-checkbox node-key="id"
             :draggable="draggable"
             :allow-drop="allowDrop"
             @node-drop="handleDrop"
             ref="menuTree"
             :default-expanded-keys="expandedKey" style="left: 100px">
     <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="node.level<=2"
                     type="text"
                     icon="el-icon-plus"
                     @click="() => append(data)">
          </el-button>
          <el-button
                     type="text"
                     icon="el-icon-edit"
                     @click="() => edit(data)">
          </el-button>
          <el-button v-if="node.childNodes.length==0"
                     type="text"
                     icon="el-icon-delete"
                     @click="() => remove(node, data)">
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      v-if="this.dialogType==='edit'?this.title='修改当前节点':this.title='新增子节点'"
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%">
      <el-form :model="category" ref="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.unit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancel">取 消</el-button>
    <el-button type="primary" @click="submitCategory">确 定</el-button>
  </span>
    </el-dialog>
  </div>

</template>

<script>
import {listCategory, delCategory, addCategory, updateCategory, getCategory,updateBatchCategory} from "@/api/product/category";

export default {
  name: "category",
  data() {
    return {
      pId: 0,
      //控制拖拽功能是否开启
      draggable: false,
      //所有修改的节点
      updateNodes: [],
      maxLevel: 0,
      //分类树数据
      categoryTree: [],
      //默认展开的数组名称
      expandedKey: [],
      //分类节点表单
      category: {
        id: null,
        name: '',
        parentId: 0,
        showStatus: 0,
        sort: 0,
        icon: '',
        unit: '',
      },
      //控制分类表单弹窗是否显示
      dialogVisible: false,

      //弹窗类型
      dialogType: "", //edit add
      //弹窗标题
      title: "",
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    };
  },
  methods: {
    batchDelete(){
      let ids=[]
      //若节点可被选择 返回目前被选中的节点组成的数组
      let checkedNodes=this.$refs.menuTree.getCheckedNodes()
      for (let i of checkedNodes){
        ids.push(i.id)
      }
      this.$modal.confirm('是否确认删除？').then(function () {
        return delCategory(ids);
      }).then(() => {
        this.getTree();
        this.$modal.msgSuccess("删除成功");
        //设置需要默认展开的菜单
        this.expandedKey = [node.parent.data.id]
      }).catch(() => {
      });
      console.log("被选中的元素",ids)

    },
    /**
     * 批量保存方法
     */
    batchSave(){
      updateBatchCategory(this.updateNodes).then(response => {
        this.$modal.msgSuccess("分类菜单顺序修改成功");
      });
      //刷新出新菜单
      this.getTree();

      //设置需要默认展开的菜单
      this.expandedKey=[this.pId]

      //清空level
      this.maxLevel=0
      this.updateNodes=[]
      this.pId=0
    },
    /**
     * 拖拽节点
     * @param draggingNode  当前节点
     * @param dropNode 放到了哪个节点的位置
     * @param type  拖拽到了哪个位置
     * @returns {boolean}
     */
    allowDrop(draggingNode, dropNode, type) {
      //1.被拖动的当前节点以及所在的父节点总层数不能大于3
     this.countNodeLevel(draggingNode.data)

      //当前正在拖动的节点+父亲节点所在的深度不大于3

      //子节点的最大level-当前节点的level+1
     let currentDeep= Math.abs(this.maxLevel-draggingNode.level)+1;

      //inner 拖到某个节点的里面
      if(type=="inner"){
        //inner 深度是相加关系  如果小于等于3 true 否则false
        console.log('this.maxLevel',this.maxLevel)
        console.log('draggingNode.data.level',draggingNode.data.level)
        console.log('draggingNode.data.level',dropNode.level)
        return  (deep+dropNode.level)<=3;
      }else {
        return (deep+dropNode.parent.level)<=3
      }
      return false;
    },

    /**
     * 拖拽成功的回调
     * @param draggingNode
     * @param dropNode
     * @param type
     * @param event
     */
    handleDrop(draggingNode, dropNode, type,event){

      //1.当前节点最新父节点的id
      let pId=0
      let siblings=null;
      //拖到前面或者后面
      if(type=="before"||type=="after"){
        pId=dropNode.parent.data.id
        siblings=dropNode.parent.childNodes
      }else {
        pId=dropNode.data.id
        siblings=dropNode.childNodes
      }
      this.pId=pId

      //2. 当前拖拽节点最新的顺序
      for (let i = 0; i <siblings.length ; i++) {
        if(siblings[i].data.id==draggingNode.data.id){
          let currentLevel=draggingNode.level
          //如果遍历的是当前正在拖拽的节点
          if(siblings[i].level!=draggingNode.level){
            //当前节点的层级发生变化
              currentLevel=siblings[i].level;

              //修改他子节点的层级
              this.updateChildNodeLevel(siblings[i])

            //继续修改子节点的层级
          }
          this.updateNodes.push({id:siblings[i].data.id,sort:i,parentId:pId,level:currentLevel})
        }else {
          this.updateNodes.push({id:siblings[i].data.id,sort:i})
        }

      }
      //3. 当前拖拽节点的最新层级
      console.log("updateNodes",this.updateNodes)

    },
    //改变子节点的层级
    updateChildNodeLevel(node){
      if(node.childNodes.length>0){
        for(let i=0;i<node.childNodes.length;i++){
          var cNode=node.childNodes[i].data;
          this.updateNodes.push({id:cNode.id,level:node.childNodes[i].level})
          this.updateChildNodeLevel(node.childNodes[i])
        }
      }



    },

    //统计当前节点层数
    countNodeLevel(node){
      //找到所有子节点，求出最大深度
      //1.判断是否有子节点
      if(node.children!=null&&node.children.length>0){
        for(let i=0;i<node.children.length;i++){
          if(node.children[i].level>this.maxLevel){
            //交换值
            this.maxLevel=node.children[i].level
          }
          this.countNodeLevel(node.children[i])
        }
      }
    },
    /**
     * 追加树节点
     * @param data
     */
    append(data) {
      this.reset();
      this.dialogVisible = true;
      this.dialogType = 'add'
      this.category.parentId = data.id
    },

    /**
     * 删除树节点
     * @param node
     * @param data
     */
    remove(node, data) {
      let ids = [data.id];
      this.$modal.confirm('是否确认删除名称为【' + data.label + '】为的数据项？').then(function () {
        return delCategory(ids);
      }).then(() => {
        this.getTree();
        this.$modal.msgSuccess("删除成功");
        //设置需要默认展开的菜单
        this.expandedKey = [node.parent.data.id]
      }).catch(() => {
      });
    },
    /** 修改树节点 */
    edit(data) {
      this.dialogVisible = true;
      this.dialogType = 'edit'
      //发送请求获取节点最新的数据
      getCategory(data.id).then(response => {
        this.category = response.data;
      });
    },
    /** 提交三级分类*/
    submitCategory: function () {
      this.$refs["category"].validate(valid => {
        if (valid) {
          if (this.category.id != undefined) {
            updateCategory(this.category).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.dialogVisible = false;
              this.getTree();
            });
          } else {
            addCategory(this.category).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getTree();
            });
          }
        }
      });
    },

    /** 查询三级分类树列表 */
    getTree() {
      this.loading = true;
      listCategory().then(response => {
        this.categoryTree = response.data
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    /** 重置按钮操作 */
    reset() {
      this.category={
        id: null,
        name: '',
        parentId: 0,
        showStatus: 0,
        sort: 0,
        icon: '',
        unit: '',
      }
    },
  },

  created() {
    this.getTree();
  }
}
</script>

<style scoped>

</style>
